//
//  SEGNewMyMessageRootViewController.m
//  ExcellentHome
//
//  Created by Andy on 16/5/30.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGNewMyMessageRootViewController.h"
#import "SEGMessageLikeViewController.h"
#import "NewMyMessageTableViewCell.h"
#import "SEGOrderMessageViewController.h"
#import "SEGSystemMessageViewController.h"
#import "SEGSessionMessageViewController.h"
#import "SEGServiceMessageViewController.h"
#import "SEGBigNavigationView.h"
#import "SEGNavMenuListView.h"
#import "SEGRedDotManager.h"
#import "SEGOperatingGuideView.h"

#import "SEGNewMyMessageRootViewModel.h"

#if __has_include(<Commom/SEGCommonConfig.h>)
#import <Commom/SEGCommonConfig.h>
#else
#import "SEGCommonConfig.h"
#endif

#if __has_include(<SEGMenus/SEGMenuNaviView.h>)
#import <SEGMenus/SEGMenuNaviView.h>
#else
#import "SEGMenuNaviView.h"
#endif
#import <SEGPlatform/SEGActivityLotteryBubbleButton.h>
#import "GDTUnifiedNativeAd.h"
#import "GDTUnifiedNativeAdView.h"
#import "UnifiedNativeAdImageView.h"

#if __has_include(<SEGMenus/SEGMenuListManager.h>)
#import <SEGMenus/SEGMenuListManager.h>
#else
#import "SEGMenuListManager.h"
#endif

#import <SEGPlatform/SEGAdDisplayManager.h>

static NSString *cellIdentifier = @"messageCell";

@interface SEGNewMyMessageRootViewController () <UITableViewDataSource, UITableViewDelegate, GDTUnifiedNativeAdDelegate, GDTUnifiedNativeAdViewDelegate>
@property (nonatomic, strong) GDTUnifiedNativeAd *unifiedNativeAd;
/// 广告数据
@property (nonatomic, strong) NSArray<GDTUnifiedNativeAdDataObject *> *adDataArray;
/// 表格
@property (nonatomic, strong) UITableView *tableView;
/// 大标题导航栏
@property (nonatomic, strong)SEGBigNavigationView *bigNavView;
/// 菜单界面
@property (nonatomic, strong)SEGNavMenuListView *navMenuListView;
/// 导航工具通用
@property (nonatomic, strong)SEGMenuNaviView *naviBarView;

/// viewModel
@property (nonatomic, strong) SEGNewMyMessageRootViewModel *viewModel;

/// manager
@property (nonatomic, strong) SEGMenuListManager *menuListManager;

@end

@implementation SEGNewMyMessageRootViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self seg_checkActivityLotteryBubble];
    [self seg_loadData];
}
- (void)viewWillDisappear :(BOOL)animated {
    [super viewWillAppear:animated];
    self.navMenuListView.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView}];
 
    if (self.isRootVC) {
        self.navDisplayType = SEGNavigationBarDisplayTypeHide;
        [self.view addSubview:self.naviBarView];
        //25891 【深到家v1.1.0】iOS 我的页面，菜单数据展示不全（见截图）
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(self.naviBarView.layout.totalHeight);
            make.left.right.bottom.equalTo(self.view);
        }];
        
    } else {
        self.title = @"消息";
        [self showCustomNavigationBackButton];
    }
    
    self.navigationItem.hidesBackButton = YES;

    /// 消息数据
    WeakSelf;
    [self.tableView addWindmillWithHeaderRefreshBlock:^{
        [weakSelf seg_loadData];
    }];
    [self seg_initMessageData];
    [self seg_showMoreMenuList];
    // 初始化通知
    [self seg_initMessgeNotification];
}

#pragma mark - Load Data
//加载数据
- (void)seg_loadData {
    @weakify(self);
    [self.viewModel.msgV3Signal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.tableView stopAnimatingWindmill];
        [self seg_initMessageData];
        // Tencent AD self.dataArray
        [self loadTencentAD];
    }];
}
/// 初始化消息数据
- (void)seg_initMessageData {
    @weakify(self);
    [self.viewModel.dataSignal subscribeNext:^(NSNumber *dataCount) {
        @strongify(self);
        if (dataCount.integerValue > 0) {
            [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.tableView}];
            // 头尾间距多出5
            UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 5.0)];
            headView.backgroundColor = kColor_W;
            self.tableView.tableHeaderView = headView;
        } else {
            // 显示空数据提示到界面上
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView}];
            
            UIView *headView = [[UIView alloc] initWithFrame:CGRectZero];
            headView.backgroundColor = kColor_W;
            self.tableView.tableHeaderView = headView;
        }
        [self.tableView reloadData];
    }];
}
/// 导航菜单数据
- (void)seg_showMoreMenuList {
    WeakSelf;
    // 展示本地数据
    
    [self.menuListManager segAsyncGetLocalDataWithAction:self.action PositionType:0 settingsId:self.settingsId finished:^(BOOL hasTopLine, BOOL hasAd, BOOL hasCommonMenu, NSArray<SEGNeighborRollViewModel *> *topLine) {
        [weakSelf refreshOtherData];
        //请求网络数据
        [self.menuListManager segReqqustMenuDataAndBusinessDataWithMenuSid:self.menuSid action:self.action PositionType:0 settingsId:self.settingsId hotNewsParams:nil targetVC:self Finished:^(BOOL hasTopLine, BOOL hasAd, BOOL hasCommonMenu, NSArray<SEGNeighborRollViewModel *> *topLine) {
            [weakSelf refreshOtherData];
//            [self showGuideView];
        }];
    }];
}

#pragma mark -  UI
/// 这里用于布局样式
-(void)refreshOtherData {
    if (self.isRootVC) {
        SEGMenuListModel *model = [SEGMenuListManager segGetNavigationBarData:[self.menuListManager.menuListDataArr mutableCopy]];
        SEGMenuNaviViewModel *data = [[SEGMenuNaviViewModel alloc] init];
        data.menuData = model;
        SEGMenuNaviViewLayout *layout = [[SEGMenuNaviViewLayout alloc] initWithData:data type:[model.widgetType integerValue]];
        [self.naviBarView setWithLayout:layout];
        
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(self.naviBarView.layout.totalHeight);
            make.left.right.bottom.equalTo(self.view);
        }];
    } else {
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
}
- (void)setUpNavButtonAndMenuView {
    if (self.menuListManager.menuListDataArr.count > 0) {
        __weak typeof (self) weakSelf = self;
        // 导航栏右侧按钮
        if (!self.bigNavView.rightButton) {
            [self.bigNavView addRightButtonWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_morelist")] tapBlock:^{
                //显示我的菜单
                weakSelf.navMenuListView.hidden = !weakSelf.navMenuListView.hidden;
            }];
        }
        //初始化菜单
        [self.navMenuListView setUpNavMenuListViewWithArray:[self.menuListManager.menuListDataArr mutableCopy] finished:^(BOOL isRedDot) {
            //更新导航栏右侧按钮的红点
            [weakSelf.bigNavView updateRightButtonRedDot:isRedDot];
        }];
    } else {
        if (self.bigNavView.rightButton) {
            self.bigNavView.rightButton.hidden = YES;
        }
    }
    //适配的导航栏高度
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(self.bigNavView.height);
        make.left.right.bottom.equalTo(self.view);
    }];
}
// 引导页
- (void)showGuideView {

}
/// 判断是否显示活动抽奖气泡
- (void)seg_checkActivityLotteryBubble {
    [[SEGUhomeMediator sharedInstance] seg_checkActivityLotteryBubble:@{@"vc" : self}];
}

#pragma mark - Init
- (void)seg_initMessgeNotification {
    // 收到活动抽奖推送
    WeakSelf;
    [[NSNotificationCenter defaultCenter] addObserverForName:SEGActivityLotteryNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf seg_checkActivityLotteryBubble];
    }];
    
    // 收到消息红点刷新
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(seg_loadData)
                                                 name:@"MESSAGELISTREFRESH"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(addOrHideRedDot:)
                                                 name:SEGAddReddotNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(addOrHideRedDot:)
                                                 name:SEGHiddenRedDotNotification
                                               object:nil];
}

#pragma mark - NSNotificationCenter
- (void)addOrHideRedDot:(NSNotification *)notification {
    if (notification.object) {
        NSArray *ids = notification.object;
        if (ids && [ids isKindOfClass:[NSArray class]]) {
            __weak typeof (self) weakSelf = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navMenuListView setUpNavMenuListViewWithArray:[self.menuListManager.menuListDataArr mutableCopy] finished:^(BOOL isRedDot) {
                    //更新导航栏右侧按钮的红点
                    [weakSelf.bigNavView updateRightButtonRedDot:isRedDot];
                }];
            });
        }
    }
}

#pragma mark - Event
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.navMenuListView.hidden = YES;
}
 
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.navMenuListView.hidden = YES;
}
#pragma mark - TableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.viewModel.dataArray count];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewMyMessageTableViewCell *cell = [[NewMyMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MessageModel *message = self.viewModel.dataArray[indexPath.row];
    NSString *number = self.viewModel.muIsReadRod[message.groupid];
    [cell showWithModel:message unReadNumber:number];
    cell.line.hidden = (indexPath.row == self.viewModel.dataArray.count-1) ?:NO;

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    self.navMenuListView.hidden = YES;
    //删除消息tab红点
    if (self.settingsId) {
        [[SEGUhomeMediator sharedInstance]seg_deleteRedDotWithId:@{@"idString":self.settingsId}];
    }
    MessageModel *messageModel = self.viewModel.dataArray[indexPath.row];
    //删除列表上的红点
    NSString *number = self.viewModel.muIsReadRod[messageModel.groupid];
    if ([number intValue] > 0) {
        [self.viewModel.muIsReadRod setObject:@"" forKey:messageModel.groupid];//设置已读
        [self.tableView reloadData];
        
        messageModel.isRead = @"1";
        // 修改数据库对应的数据为已读(不放到子线程 防止数据库操作冲突)
        [[MessageDataBaseModel sharedDataBaseModel] updateMessagesToReadInDataBaseWithGroupId:messageModel.groupid];
    }
    
    [self onMyMessageAction:messageModel];
}
#pragma mark -界面跳转
- (void)onMyMessageAction:(MessageModel *)msgModel {
    if ([msgModel.groupid hasPrefix:kMessageGroupSystemPre]) { //系统消息
        SEGSystemMessageViewController* systemMessageVC = [[SEGSystemMessageViewController alloc] init];
        systemMessageVC.groupId = msgModel.groupid;
        systemMessageVC.type = SEGMessageVCType_System;
        systemMessageVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemMessageVC animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupRadioPre]) { //帮帮广播 ---
        SEGSystemMessageViewController* systemMessageVC = [[SEGSystemMessageViewController alloc] init];
        systemMessageVC.groupId = msgModel.groupid;
        systemMessageVC.type = SEGMessageVCType_Radio;
        systemMessageVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemMessageVC animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupActivity]) { //活动通知
        SEGSystemMessageViewController* systemMessageVC = [[SEGSystemMessageViewController alloc] init];
        systemMessageVC.groupId = msgModel.groupid;
        systemMessageVC.type = SEGMessageVCType_Activity;
        systemMessageVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemMessageVC animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupServicePre]) { //服务号
        SEGServiceMessageViewController* serviceMessageVC = [[SEGServiceMessageViewController alloc] init];
        serviceMessageVC.baseInfoModel = [SEGCommonConfig shared].isHideServiceMessage ? [MessageRequestModel sharedRequestModel].serviceBaseInfoModel : [SEGServicenbrbaseinfoManager sharedManager].ServicenbrBaseInfo;
        serviceMessageVC.groupId = msgModel.groupid;
        serviceMessageVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:serviceMessageVC animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupTaskPre]) { //活动任务中奖记录
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initMissionRecordListViewController:nil];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupPrizePre]) { //中奖记录
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWinRecordListViewController:nil];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupRadioReviewPre]) { //帮帮审核通知
        SEGSystemMessageViewController* systemMessageVC = [[SEGSystemMessageViewController alloc] init];
        systemMessageVC.groupId = msgModel.groupid;
        systemMessageVC.type = SEGMessageVCType_HelpCheck;
        systemMessageVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemMessageVC animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupRecommendPre]) { //精选推荐
        SEGSystemMessageViewController* systemMessageVC = [[SEGSystemMessageViewController alloc] init];
        systemMessageVC.groupId = msgModel.groupid;
        systemMessageVC.type = SEGMessageVCType_Recommend;
        systemMessageVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemMessageVC animated:YES];
        return;
    } else if ([msgModel.groupid hasPrefix:kMessageGroupMall]) { //商场消息
        SEGSystemMessageViewController* systemMessageVC = [[SEGSystemMessageViewController alloc] init];
        systemMessageVC.groupId = msgModel.groupid;
        systemMessageVC.type = SEGMessageVCType_Mall;
        systemMessageVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemMessageVC animated:YES];
        return;
    }
    
    // 根据type跳转页面
    [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithMessageType:@{@"model":msgModel, @"nav":self.navigationController}];
}

#pragma mark - 腾讯广告
- (BOOL)hasTencentViewInTableViewFooterView {
    BOOL hasTencentAD = NO;
    if ([self.tableView.tableFooterView isKindOfClass:[UnifiedNativeAdImageView class]]) {
        hasTencentAD = YES;
    }
    return hasTencentAD;
}
- (void)loadTencentAD {
    // 1. 判断列表是否存在数据，不存在不加载腾讯广告
    if (self.viewModel.dataArray.count <= 0) return;
    // 2. 读取本地广告配置，是否可以展示广告
    if (![[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_MessageListType]) return;
    // 3. 判断本地是否已经有广告视图
    if ([self hasTencentViewInTableViewFooterView]) return;
    
    self.unifiedNativeAd = [[GDTUnifiedNativeAd alloc] initWithPlacementId:kGDTPosIdMessageBottomCell];
    self.unifiedNativeAd.delegate = self;
    [self.unifiedNativeAd loadAd];
}

#pragma mark - GDTUnifiedNativeAdDelegate
- (void)gdt_unifiedNativeAdLoaded:(NSArray<GDTUnifiedNativeAdDataObject *> * _Nullable)unifiedNativeAdDataObjects error:(NSError * _Nullable)error {
    NSLog(@"广告数据回调,%s",__FUNCTION__);
    if (!error && unifiedNativeAdDataObjects.count > 0) {
        NSLog(@"成功请求到广告数据:%zd",unifiedNativeAdDataObjects.count);
        self.adDataArray = unifiedNativeAdDataObjects;
        if (self.adDataArray && self.adDataArray.count > 0) {
            GDTUnifiedNativeAdDataObject *dataObject = self.adDataArray.firstObject;
            UnifiedNativeAdImageView *adView = [[UnifiedNativeAdImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, UnifiedNativeAdImageViewHeight)];
            [adView setupWithUnifiedNativeAdDataObject:dataObject delegate:self vc:self];
            [self.tableView setTableFooterView:adView];
        }
        return;
    }
    NSLog(@"广告数据回调,%s,%@",__FUNCTION__,error.localizedDescription);
}
#pragma mark - GDTUnifiedNativeAdViewDelegate
- (void)gdt_unifiedNativeAdViewWillExpose:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告曝光回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdViewDidClick:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告点击回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdDetailViewClosed:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告详情页关闭回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdViewApplicationWillEnterBackground:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"当点击应用下载或者广告调用系统程序打开时调用,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdDetailViewWillPresentScreen:(GDTUnifiedNativeAdView *)unifiedNativeAdView{
  NSLog(@"广告详情页面即将展示回调,%s",__FUNCTION__);
}
- (void)gdt_unifiedNativeAdView:(GDTUnifiedNativeAdView *)unifiedNativeAdView playerStatusChanged:(GDTMediaPlayerStatus)status userInfo:(NSDictionary *)userInfo{
  NSLog(@"视频广告播放状态更改回调,%s",__FUNCTION__);
}

#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        CGRect rect = CGRectZero;
        rect = CGRectMake(0, KBigNavHeight, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - KBigNavHeight);
        _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = kColor_L2;
        _tableView.backgroundColor = kColor_W;

        _tableView.rowHeight = 66;
        [_tableView registerClass:[NewMyMessageTableViewCell class] forCellReuseIdentifier:cellIdentifier];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //适配iOS11
        if(@available(iOS 11.0, *)){
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight  = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _tableView;
}
- (SEGBigNavigationView *)bigNavView {
    if (!_bigNavView) {
        _bigNavView = [[SEGBigNavigationView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), KBigNavHeight)];
        _bigNavView.hidden = YES;
        [self.view addSubview:_bigNavView];
    }
    return _bigNavView;
}
- (SEGNavMenuListView *)navMenuListView {
    if (!_navMenuListView) {
        _navMenuListView = [[SEGNavMenuListView alloc] init];
        [self.view addSubview:_navMenuListView];
        _navMenuListView.hidden = YES;
    }
    return _navMenuListView;
}
- (SEGMenuNaviView *)naviBarView {
    if (!_naviBarView) {
        SEGMenuNaviViewModel *data = [[SEGMenuNaviViewModel alloc] init];
        SEGMenuNaviViewLayout *layout = [[SEGMenuNaviViewLayout alloc]initWithData:data type:SEGEnumShowTypeNavigationBar_99003];
        _naviBarView = [[SEGMenuNaviView alloc]initWithFrame:CGRectZero];
        [_naviBarView setWithLayout:layout];
    }
    return _naviBarView;
}
- (SEGNewMyMessageRootViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGNewMyMessageRootViewModel alloc] init];
    return _viewModel;
}
- (SEGMenuListManager *)menuListManager {
    if (!_menuListManager) _menuListManager = [SEGMenuListManager new];
    return _menuListManager;
}

@end
